/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DataAccess;

import java.sql.*;
import javax.swing.JOptionPane;

/**
 */
public class Connect {

    private String url;
    private String userName = "";
    private String passWord = "";
    private String databaseName = "";
    private String serverName = "";
    private static Connection conn = null;

    /**
     * load property to connect from configs file
     */
    public Connect() {
        this.url = "jdbc:sqlserver://";
        if (Configs.loadConfigurations()) {
            serverName = Configs.getProperty(Configs.CONFIG_SERVERNAME);
            userName = Configs.getProperty(Configs.CONFIG_SERVERUSERNAME);
            passWord = Configs.getProperty(Configs.CONFIG_SERVERPASSWORD);
            databaseName = Configs.getProperty(Configs.CONFIG_DATABASENAME);
        } else{
            JOptionPane.showMessageDialog(null, "Load configs has been error!!");
        }

    }

    public Connect(String serverName, String username, String password, String database) {
        this.url = "jdbc:sqlserver://";
        this.databaseName = database;
        this.passWord = password;
        this.serverName = serverName;
        this.userName = username;
    }

    public static Connection getConn() {
        return conn;
    }

    /**
     * Check connect to database
     * @return booleam
     */
    public boolean openConnection() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection(getUrl(), userName, passWord);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    public static void closeDB() {
        try {
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getUrl() {
        return url + serverName + ";databaseName=" + databaseName;
    }
}
